/**
 * 
 */
package vn.com.demand.lux.view;

import java.io.File;
import java.io.IOException;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import jxl.Workbook;
import jxl.format.Alignment;
import jxl.format.Colour;
import jxl.format.UnderlineStyle;
import jxl.format.VerticalAlignment;
import jxl.write.Blank;
import jxl.write.DateFormat;
import jxl.write.WritableCellFormat;
import jxl.write.WritableFont;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import jxl.write.WriteException;
import jxl.write.biff.RowsExceededException;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.ResultSetHandler;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.jface.dialogs.Dialog;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.viewers.IStructuredContentProvider;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.nebula.widgets.datechooser.DateChooserCombo;
import org.eclipse.nebula.widgets.formattedtext.DateFormatter;
import org.eclipse.nebula.widgets.formattedtext.FormattedText;
import org.eclipse.nebula.widgets.formattedtext.TimeFormatter;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.KeyEvent;
import org.eclipse.swt.events.KeyListener;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.layout.FormAttachment;
import org.eclipse.swt.layout.FormData;
import org.eclipse.swt.layout.FormLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.FileDialog;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.MessageBox;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.swt.widgets.Text;
import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.IEditorSite;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.forms.widgets.Form;
import org.eclipse.ui.forms.widgets.FormToolkit;
import org.eclipse.ui.forms.widgets.Section;
import org.eclipse.ui.part.EditorPart;

import vn.com.demand.lux.Activator;
import vn.com.demand.lux.criteria.ServiceCardCriteria;
import vn.com.demand.lux.model.CustomerBean;
import vn.com.demand.lux.model.ServiceCardBean;
import vn.com.demand.lux.model.ServiceCardManager;
import vn.com.demand.lux.view.labelprovider.ServiceCardLabelProvider;
import vn.com.demand.util.DpUtils;
import vn.com.demand.widget.SearchableDialogActivator;
import vn.com.demand.widget.SelectCustomerHeader;
import vn.com.demand.widget.SelectItemCodeHeader;
import vn.com.demand.widget.SearcheableTable.MyModel;

import com.swtdesigner.ResourceManager;
import com.swtdesigner.SWTResourceManager;

/**
 * @author Nguyen The Thinh
 *
 */
public class ServiceCardEditor extends EditorPart {

	private Text address;
	private Text customerName;
	private Text inputAddress;
	private Text inputFullName;
	private Table table;
	private Text inputType;
	private Text inputServiceDetail;
	private Text inputContractNumber;
	private Text inputCustomerName;
	private Text inputCustomerCode;
	private Text inputTo;
	private Text inputFrom;
	private DateChooserCombo inputDate;
	private Text inputResourceID;
	private Text inputCardNumber;
	private SearchableDialogActivator customerCode;
	private SearchableDialogActivator contract;
	private Text serviceCard;
	private SearchableDialogActivator resource;
	private DateChooserCombo toDate;
	private DateChooserCombo fromDate;
	public static final String ID = "vn.com.demand.lux.view.ServiceCardEditor"; //$NON-NLS-1$
	private List<ServiceCardBean> inputList;
	private ArrayList<ServiceCardBean> updateList = new ArrayList<ServiceCardBean>();
	private FormattedText fromTextFormat;
	private FormattedText toTextFormat;
	private ServiceCardCriteria criteria = new ServiceCardCriteria();
	private TableViewer tableViewer;
	//Use this Id to load entry u want to edit
	private int cardId = 0;
	private Section entereditServiceCardSection;
	private Section generalInformationSection;
	/**
	 * Create contents of the editor part
	 * @param parent
	 */
	@Override
	public void createPartControl(Composite parent) {
		FormToolkit toolkit = new FormToolkit(Display.getCurrent());
		Composite container = toolkit.createComposite(parent, SWT.NONE);
		container.setLayout(new FillLayout());

		final Form serviceCardForm = toolkit.createForm(container);
		final Composite body = serviceCardForm.getBody();
		body.setLayout(new FormLayout());
		toolkit.paintBordersFor(body);

		generalInformationSection = toolkit.createSection(body, Section.TWISTIE | Section.EXPANDED | Section.TITLE_BAR | Section.FOCUS_TITLE);
		final FormData fd_generalInformationSection = new FormData();
		fd_generalInformationSection.right = new FormAttachment(100, -5);
		fd_generalInformationSection.left = new FormAttachment(0, 5);
		generalInformationSection.setLayoutData(fd_generalInformationSection);
		generalInformationSection.setText("General Information");

		final Composite composite = toolkit.createComposite(generalInformationSection, SWT.BORDER);
		composite.setLayout(new FormLayout());
		generalInformationSection.setClient(composite);
		toolkit.paintBordersFor(composite);

		final Label fromDateLabel = toolkit.createLabel(composite, "From date", SWT.NONE);
		final FormData fd_fromDateLabel = new FormData();
		fd_fromDateLabel.bottom = new FormAttachment(0, 88);
		fd_fromDateLabel.top = new FormAttachment(0, 75);
		fd_fromDateLabel.right = new FormAttachment(0, 60);
		fd_fromDateLabel.left = new FormAttachment(0, 11);
		fromDateLabel.setLayoutData(fd_fromDateLabel);
		fromDateLabel.setForeground(SWTResourceManager.getColor(0, 0, 255));
		fromDateLabel.setFont(SWTResourceManager.getFont("Tahoma", 8, SWT.NONE));

		fromDate = new DateChooserCombo(composite, SWT.BORDER);
		final FormData fd_fromDate = new FormData();
		fd_fromDate.bottom = new FormAttachment(0, 94);
		fd_fromDate.top = new FormAttachment(0, 75);
		fd_fromDate.right = new FormAttachment(0, 232);
		fd_fromDate.left = new FormAttachment(0, 90);
		fromDate.setLayoutData(fd_fromDate);
		fromDate.setFormatter(new DateFormatter(Activator.getDefault().getDateFormatTypePreferences()));

		final Label fromDateLabel_1 = toolkit.createLabel(composite, "To date", SWT.NONE);
		final FormData fd_fromDateLabel_1 = new FormData();
		fd_fromDateLabel_1.bottom = new FormAttachment(0, 88);
		fd_fromDateLabel_1.top = new FormAttachment(0, 75);
		fd_fromDateLabel_1.right = new FormAttachment(0, 343);
		fd_fromDateLabel_1.left = new FormAttachment(0, 294);
		fromDateLabel_1.setLayoutData(fd_fromDateLabel_1);
		fromDateLabel_1.setForeground(SWTResourceManager.getColor(0, 0, 255));
		fromDateLabel_1.setFont(SWTResourceManager.getFont("Tahoma", 8, SWT.NONE));

		toDate = new DateChooserCombo(composite, SWT.BORDER);
		final FormData fd_toDate = new FormData();
		fd_toDate.bottom = new FormAttachment(0, 94);
		fd_toDate.top = new FormAttachment(0, 75);
		fd_toDate.right = new FormAttachment(0, 527);
		fd_toDate.left = new FormAttachment(0, 375);
		toDate.setLayoutData(fd_toDate);
		toDate.setFormatter(new DateFormatter(Activator.getDefault().getDateFormatTypePreferences()));
		toolkit.adapt(toDate);

		final Label fromDateLabel_2 = toolkit.createLabel(composite, "Resource", SWT.NONE);
		final FormData fd_fromDateLabel_2 = new FormData();
		fd_fromDateLabel_2.bottom = new FormAttachment(0, 24);
		fd_fromDateLabel_2.top = new FormAttachment(0, 11);
		fd_fromDateLabel_2.right = new FormAttachment(0, 343);
		fd_fromDateLabel_2.left = new FormAttachment(0, 294);
		fromDateLabel_2.setLayoutData(fd_fromDateLabel_2);
		fromDateLabel_2.setForeground(SWTResourceManager.getColor(0, 0, 255));
		fromDateLabel_2.setFont(SWTResourceManager.getFont("Tahoma", 8, SWT.NONE));

//		resource = toolkit.createText(composite, null, SWT.NONE);
		SelectItemCodeHeader resourceHeader = new SelectItemCodeHeader(null, "select res_id as code, fullname as description from demand_resourcelist order by code");
		resource = new SearchableDialogActivator(composite, SWT.NONE, resourceHeader);
		final FormData fd_resource = new FormData();
		fd_resource.bottom = new FormAttachment(0, 31);
		fd_resource.top = new FormAttachment(0, 11);
		fd_resource.right = new FormAttachment(0, 554);
		fd_resource.left = new FormAttachment(0, 375);
		resource.setLayoutData(fd_resource);

		final Label fromDateLabel_2_1 = toolkit.createLabel(composite, "Service card", SWT.NONE);
		final FormData fd_fromDateLabel_2_1 = new FormData();
		fd_fromDateLabel_2_1.bottom = new FormAttachment(0, 24);
		fd_fromDateLabel_2_1.top = new FormAttachment(0, 11);
		fd_fromDateLabel_2_1.right = new FormAttachment(0, 70);
		fd_fromDateLabel_2_1.left = new FormAttachment(0, 10);
		fromDateLabel_2_1.setLayoutData(fd_fromDateLabel_2_1);
		fromDateLabel_2_1.setForeground(SWTResourceManager.getColor(0, 0, 255));
		fromDateLabel_2_1.setFont(SWTResourceManager.getFont("Tahoma", 8, SWT.NONE));

		serviceCard = toolkit.createText(composite, null, SWT.NONE);
		final FormData fd_serviceCard = new FormData();
		fd_serviceCard.bottom = new FormAttachment(0, 30);
		fd_serviceCard.top = new FormAttachment(0, 11);
		fd_serviceCard.right = new FormAttachment(0, 232);
		fd_serviceCard.left = new FormAttachment(0, 90);
		serviceCard.setLayoutData(fd_serviceCard);

		Label fromDateLabel_2_2;
		fromDateLabel_2_2 = toolkit.createLabel(composite, "Contract", SWT.NONE);
		final FormData fd_fromDateLabel_2_2 = new FormData();
		fd_fromDateLabel_2_2.bottom = new FormAttachment(0, 54);
		fd_fromDateLabel_2_2.top = new FormAttachment(0, 41);
		fd_fromDateLabel_2_2.right = new FormAttachment(0, 343);
		fd_fromDateLabel_2_2.left = new FormAttachment(0, 294);
		fromDateLabel_2_2.setLayoutData(fd_fromDateLabel_2_2);
		fromDateLabel_2_2.setForeground(SWTResourceManager.getColor(0, 0, 255));
		fromDateLabel_2_2.setFont(SWTResourceManager.getFont("Tahoma", 8, SWT.NONE));

//		contract = toolkit.createText(composite, null, SWT.NONE);
		SelectItemCodeHeader contractHeader = new SelectItemCodeHeader(null, "select contractnumber as code, contractdescription as description from demand_contractinformation");
		contract = new SearchableDialogActivator(composite, SWT.NONE, contractHeader);
		final FormData fd_contract = new FormData();
		fd_contract.bottom = new FormAttachment(0, 61);
		fd_contract.top = new FormAttachment(0, 41);
		fd_contract.right = new FormAttachment(0, 554);
		fd_contract.left = new FormAttachment(0, 375);
		contract.setLayoutData(fd_contract);

		Label fromDateLabel_2_1_1;
		fromDateLabel_2_1_1 = toolkit.createLabel(composite, "Customer code", SWT.NONE);
		final FormData fd_fromDateLabel_2_1_1 = new FormData();
		fd_fromDateLabel_2_1_1.bottom = new FormAttachment(0, 54);
		fd_fromDateLabel_2_1_1.top = new FormAttachment(0, 41);
		fd_fromDateLabel_2_1_1.right = new FormAttachment(0, 82);
		fd_fromDateLabel_2_1_1.left = new FormAttachment(0, 10);
		fromDateLabel_2_1_1.setLayoutData(fd_fromDateLabel_2_1_1);
		fromDateLabel_2_1_1.setForeground(SWTResourceManager.getColor(0, 0, 255));
		fromDateLabel_2_1_1.setFont(SWTResourceManager.getFont("Tahoma", 8, SWT.NONE));

//		customerCode = toolkit.createText(composite, null, SWT.NONE);
		SelectItemCodeHeader customerHeader = new SelectItemCodeHeader(null, "select cmp_code as code, cmp_name as description from Demand_CustomerList order by code");
		customerCode = new SearchableDialogActivator(composite, SWT.NONE, customerHeader);
		final FormData fd_customerCode = new FormData();
		fd_customerCode.bottom = new FormAttachment(0, 61);
		fd_customerCode.top = new FormAttachment(0, 41);
		fd_customerCode.right = new FormAttachment(0, 232);
		fd_customerCode.left = new FormAttachment(0, 90);
		customerCode.setLayoutData(fd_customerCode);

		Composite giButtonBar;
		giButtonBar = new Composite(composite, SWT.NONE);
		final FormData fd_giButtonBar = new FormData();
		fd_giButtonBar.bottom = new FormAttachment(0, 135);
		fd_giButtonBar.top = new FormAttachment(0, 111);
		fd_giButtonBar.right = new FormAttachment(0, 156);
		fd_giButtonBar.left = new FormAttachment(0, 11);
		giButtonBar.setLayoutData(fd_giButtonBar);
		giButtonBar.setLayout(new FillLayout());
		toolkit.adapt(giButtonBar);

		final Button giSearchButton = toolkit.createButton(giButtonBar, "Searc&h", SWT.NONE);
		giSearchButton.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(SelectionEvent e) {
				doSearch();
			}
		});
		giSearchButton.setImage(ResourceManager.getPluginImage(Activator.getDefault(), "icons/actions/viewmag+.png"));

		final Button giClearButton = toolkit.createButton(giButtonBar, "Clear", SWT.NONE);
		giClearButton.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(SelectionEvent e) {
				doClearCriteriaSection();
			}
		});
		giClearButton.setImage(ResourceManager.getPluginImage(Activator.getDefault(), "icons/actions/eraser.png"));

		final Label fromDateLabel_2_2_1 = toolkit.createLabel(composite, "Customer Name", SWT.NONE);
		final FormData fd_fromDateLabel_2_2_1 = new FormData();
		fd_fromDateLabel_2_2_1.bottom = new FormAttachment(0, 24);
		fd_fromDateLabel_2_2_1.top = new FormAttachment(0, 11);
		fd_fromDateLabel_2_2_1.right = new FormAttachment(0, 679);
		fd_fromDateLabel_2_2_1.left = new FormAttachment(0, 603);
		fromDateLabel_2_2_1.setLayoutData(fd_fromDateLabel_2_2_1);
		fromDateLabel_2_2_1.setForeground(SWTResourceManager.getColor(0, 0, 255));
		fromDateLabel_2_2_1.setFont(SWTResourceManager.getFont("Tahoma", 8, SWT.NONE));

		customerName = toolkit.createText(composite, null, SWT.NONE);
		final FormData fd_customerName = new FormData();
		fd_customerName.bottom = new FormAttachment(0, 30);
		fd_customerName.top = new FormAttachment(0, 11);
		fd_customerName.right = new FormAttachment(0, 900);
		fd_customerName.left = new FormAttachment(0, 686);
		customerName.setLayoutData(fd_customerName);

		final Label fromDateLabel_2_2_1_1 = toolkit.createLabel(composite, "Address", SWT.NONE);
		final FormData fd_fromDateLabel_2_2_1_1 = new FormData();
		fd_fromDateLabel_2_2_1_1.bottom = new FormAttachment(0, 54);
		fd_fromDateLabel_2_2_1_1.top = new FormAttachment(0, 41);
		fd_fromDateLabel_2_2_1_1.right = new FormAttachment(0, 652);
		fd_fromDateLabel_2_2_1_1.left = new FormAttachment(0, 603);
		fromDateLabel_2_2_1_1.setLayoutData(fd_fromDateLabel_2_2_1_1);
		fromDateLabel_2_2_1_1.setForeground(SWTResourceManager.getColor(0, 0, 255));
		fromDateLabel_2_2_1_1.setFont(SWTResourceManager.getFont("Tahoma", 8, SWT.NONE));

		address = toolkit.createText(composite, null, SWT.NONE);
		final FormData fd_address = new FormData();
		fd_address.bottom = new FormAttachment(0, 60);
		fd_address.top = new FormAttachment(0, 41);
		fd_address.right = new FormAttachment(0, 900);
		fd_address.left = new FormAttachment(0, 686);
		address.setLayoutData(fd_address);

		Section detailSection;
		detailSection = toolkit.createSection(body, Section.TWISTIE | Section.EXPANDED | Section.TITLE_BAR | Section.FOCUS_TITLE);
		final FormData fd_detailSection = new FormData();
		fd_detailSection.top = new FormAttachment(generalInformationSection, 0, SWT.BOTTOM);
		fd_detailSection.left = new FormAttachment(0, 5);
		fd_detailSection.right = new FormAttachment(100, -5);
		detailSection.setLayoutData(fd_detailSection);
		detailSection.setText("Detail");

		final Composite detailComposite = toolkit.createComposite(detailSection, SWT.NONE);
		detailComposite.setLayout(new FillLayout());
		detailSection.setClient(detailComposite);
		toolkit.paintBordersFor(detailComposite);

		tableViewer = new TableViewer(detailComposite, SWT.FULL_SELECTION | SWT.BORDER);
		table = tableViewer.getTable();
		toolkit.adapt(table, true, true);
		table.setLinesVisible(true);
		table.setHeaderVisible(true);
		tableViewer.setContentProvider(new ServiceCardContentProvider());
		tableViewer.setLabelProvider(new ServiceCardLabelProvider());

		final TableColumn newColumnTableColumn_9 = new TableColumn(table, SWT.NONE);
		newColumnTableColumn_9.setWidth(100);
		newColumnTableColumn_9.setText("Card number");

		final TableColumn newColumnTableColumn_8 = new TableColumn(table, SWT.NONE);
		newColumnTableColumn_8.setWidth(100);
		newColumnTableColumn_8.setText("Resource ID");
		
		final TableColumn fullNameTableColumn = new TableColumn(table, SWT.NONE);
		fullNameTableColumn.setWidth(130);
		fullNameTableColumn.setText("Fullname");

		final TableColumn newColumnTableColumn_7 = new TableColumn(table, SWT.NONE);
		newColumnTableColumn_7.setWidth(100);
		newColumnTableColumn_7.setText("Date");

		final TableColumn newColumnTableColumn_6 = new TableColumn(table, SWT.NONE);
		newColumnTableColumn_6.setWidth(100);
		newColumnTableColumn_6.setText("From");

		final TableColumn newColumnTableColumn_5 = new TableColumn(table, SWT.NONE);
		newColumnTableColumn_5.setWidth(100);
		newColumnTableColumn_5.setText("To");

		final TableColumn newColumnTableColumn_4 = new TableColumn(table, SWT.NONE);
		newColumnTableColumn_4.setWidth(100);
		newColumnTableColumn_4.setText("Customer code");

		final TableColumn newColumnTableColumn_3 = new TableColumn(table, SWT.NONE);
		newColumnTableColumn_3.setWidth(100);
		newColumnTableColumn_3.setText("Customer name");
		
		final TableColumn addressTableColumn = new TableColumn(table, SWT.NONE);
		addressTableColumn.setWidth(100);
		addressTableColumn.setText("Address");

		final TableColumn newColumnTableColumn_2 = new TableColumn(table, SWT.NONE);
		newColumnTableColumn_2.setWidth(100);
		newColumnTableColumn_2.setText("Contract number");

		final TableColumn newColumnTableColumn_1 = new TableColumn(table, SWT.NONE);
		newColumnTableColumn_1.setWidth(100);
		newColumnTableColumn_1.setText("Service detail");

		final TableColumn newColumnTableColumn = new TableColumn(table, SWT.NONE);
		newColumnTableColumn.setWidth(100);
		newColumnTableColumn.setText("Type");
		
		Composite buttonBar;
		buttonBar = toolkit.createComposite(body, SWT.NONE);
		fd_detailSection.bottom = new FormAttachment(buttonBar, -5, SWT.TOP);
		buttonBar.setLayout(new FillLayout());
		final FormData fd_buttonBar = new FormData();
		fd_buttonBar.left = new FormAttachment(100, -318);
		fd_buttonBar.top = new FormAttachment(100, -27);
		fd_buttonBar.right = new FormAttachment(100, -5);
		fd_buttonBar.bottom = new FormAttachment(100, -5);
		buttonBar.setLayoutData(fd_buttonBar);
		toolkit.paintBordersFor(buttonBar);

		final Button newButton = toolkit.createButton(buttonBar, "&New", SWT.NONE);
		newButton.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(SelectionEvent e) {
				doNew();
			}
		});
		newButton.setImage(ResourceManager.getPluginImage(Activator.getDefault(), "icons/actions/window_new.png"));

		final Button editButton = toolkit.createButton(buttonBar, "Edi&t", SWT.NONE);
		editButton.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(SelectionEvent e) {
				doEdit();
			}
		});
		editButton.setImage(ResourceManager.getPluginImage(Activator.getDefault(), "icons/actions/kate.png"));

		final Button button = toolkit.createButton(buttonBar, "&Delete", SWT.NONE);
		button.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(SelectionEvent e) {
				doDelete();
			}
		});
		button.setImage(ResourceManager.getPluginImage(Activator.getDefault(), "icons/actions/14_layer_deletelayer.png"));

		final Button exportButton = toolkit.createButton(buttonBar, "E&xport", SWT.NONE);
		exportButton.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(SelectionEvent e) {
				doExport();
			}
		});
		exportButton.setImage(ResourceManager.getPluginImage(Activator.getDefault(), "icons/actions/excel.gif"));

		final Button closeButton = toolkit.createButton(buttonBar, "Clos&e", SWT.NONE);
		closeButton.setImage(ResourceManager.getPluginImage(Activator.getDefault(), "icons/actions/shutdown.png"));
		closeButton.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(SelectionEvent e) {
				doClose();
			}
		});

		entereditServiceCardSection = toolkit.createSection(body, Section.TWISTIE | Section.TITLE_BAR | Section.FOCUS_TITLE);
		fd_generalInformationSection.top = new FormAttachment(entereditServiceCardSection, 0, SWT.BOTTOM);
		final FormData fd_entereditServiceCardSection = new FormData();
		fd_entereditServiceCardSection.top = new FormAttachment(0, 5);
		fd_entereditServiceCardSection.right = new FormAttachment(100, -5);
		fd_entereditServiceCardSection.left = new FormAttachment(generalInformationSection, 0, SWT.LEFT);
		entereditServiceCardSection.setLayoutData(fd_entereditServiceCardSection);
		entereditServiceCardSection.setText("Enter/Edit Service Card");

		final Composite inputComposite = toolkit.createComposite(entereditServiceCardSection, SWT.BORDER);
		inputComposite.setLayout(new FormLayout());
		entereditServiceCardSection.setClient(inputComposite);
		toolkit.paintBordersFor(inputComposite);

		final Label cardNumberLabel = toolkit.createLabel(inputComposite, "Card number", SWT.NONE);
		final FormData fd_cardNumberLabel = new FormData();
		fd_cardNumberLabel.bottom = new FormAttachment(0, 23);
		fd_cardNumberLabel.top = new FormAttachment(0, 10);
		fd_cardNumberLabel.right = new FormAttachment(0, 72);
		fd_cardNumberLabel.left = new FormAttachment(0, 10);
		cardNumberLabel.setLayoutData(fd_cardNumberLabel);
		cardNumberLabel.setForeground(SWTResourceManager.getColor(0, 0, 255));
		cardNumberLabel.setFont(SWTResourceManager.getFont("Tahoma", 8, SWT.NONE));

		inputCardNumber = toolkit.createText(inputComposite, null, SWT.NONE);
		final FormData fd_inputCardNumber = new FormData();
		fd_inputCardNumber.bottom = new FormAttachment(0, 29);
		fd_inputCardNumber.top = new FormAttachment(0, 10);
		fd_inputCardNumber.right = new FormAttachment(0, 240);
		fd_inputCardNumber.left = new FormAttachment(0, 98);
		inputCardNumber.setLayoutData(fd_inputCardNumber);
		inputCardNumber.addKeyListener(new KeyListener() {

			public void keyPressed(KeyEvent e) {
			}

			public void keyReleased(KeyEvent e) {
				setDirty(true);
			}
			
		});
		final Label resourceIDLabel = toolkit.createLabel(inputComposite, "Resource ID", SWT.NONE);
		final FormData fd_resourceIDLabel = new FormData();
		fd_resourceIDLabel.bottom = new FormAttachment(0, 23);
		fd_resourceIDLabel.top = new FormAttachment(0, 10);
		fd_resourceIDLabel.right = new FormAttachment(0, 364);
		fd_resourceIDLabel.left = new FormAttachment(0, 294);
		resourceIDLabel.setLayoutData(fd_resourceIDLabel);
		resourceIDLabel.setForeground(SWTResourceManager.getColor(0, 0, 255));
		resourceIDLabel.setFont(SWTResourceManager.getFont("Tahoma", 8, SWT.NONE));

		inputResourceID = toolkit.createText(inputComposite, null, SWT.NONE);
		final FormData fd_inputResourceID = new FormData();
		fd_inputResourceID.bottom = new FormAttachment(0, 29);
		fd_inputResourceID.top = new FormAttachment(0, 10);
		fd_inputResourceID.right = new FormAttachment(0, 528);
		fd_inputResourceID.left = new FormAttachment(0, 375);
		inputResourceID.setLayoutData(fd_inputResourceID);
		inputResourceID.addKeyListener(new KeyListener() {

			public void keyPressed(KeyEvent e) {
				if (e.keyCode == SWT.F5) {
					doSelectResourceId();
				}
			}

			public void keyReleased(KeyEvent e) {
				setDirty(true);
			}
			
		});
		
		final Label fullNameLabel = toolkit.createLabel(inputComposite, "Fullname", SWT.NONE);
		final FormData fd_fullNameLabel = new FormData();
		fd_fullNameLabel.bottom = new FormAttachment(0, 23);
		fd_fullNameLabel.top = new FormAttachment(0, 10);
		fd_fullNameLabel.right = new FormAttachment(0, 665);
		fd_fullNameLabel.left = new FormAttachment(0, 603);
		fullNameLabel.setLayoutData(fd_fullNameLabel);
		fullNameLabel.setForeground(SWTResourceManager.getColor(0, 0, 255));
		fullNameLabel.setFont(SWTResourceManager.getFont("Tahoma", 8, SWT.NONE));

		inputFullName = toolkit.createText(inputComposite, null, SWT.READ_ONLY);
		final FormData fd_inputFullName = new FormData();
		fd_inputFullName.bottom = new FormAttachment(0, 29);
		fd_inputFullName.top = new FormAttachment(0, 10);
		fd_inputFullName.right = new FormAttachment(0, 900);
		fd_inputFullName.left = new FormAttachment(0, 678);
		inputFullName.setLayoutData(fd_inputFullName);
		inputFullName.setEditable(false);
		
		final Label customerCodeLabel = toolkit.createLabel(inputComposite, "Customer code", SWT.NONE);
		final FormData fd_customerCodeLabel = new FormData();
		fd_customerCodeLabel.bottom = new FormAttachment(0, 52);
		fd_customerCodeLabel.top = new FormAttachment(0, 39);
		fd_customerCodeLabel.right = new FormAttachment(0, 86);
		fd_customerCodeLabel.left = new FormAttachment(0, 10);
		customerCodeLabel.setLayoutData(fd_customerCodeLabel);
		customerCodeLabel.setForeground(SWTResourceManager.getColor(0, 0, 255));
		customerCodeLabel.setFont(SWTResourceManager.getFont("Tahoma", 8, SWT.NONE));

		inputCustomerCode = toolkit.createText(inputComposite, null, SWT.NONE);
		final FormData fd_inputCustomerCode = new FormData();
		fd_inputCustomerCode.bottom = new FormAttachment(0, 58);
		fd_inputCustomerCode.top = new FormAttachment(0, 39);
		fd_inputCustomerCode.right = new FormAttachment(0, 213);
		fd_inputCustomerCode.left = new FormAttachment(0, 98);
		inputCustomerCode.setLayoutData(fd_inputCustomerCode);
		inputCustomerCode.addKeyListener(new KeyListener() {

			public void keyPressed(KeyEvent e) {
				if (e.keyCode == SWT.F5) {
					doSelectCustomerCode();
				}
			}

			public void keyReleased(KeyEvent e) {
				setDirty(true);
			}
			
		});

		final Label customerNameLabel = toolkit.createLabel(inputComposite, "Customer name", SWT.NONE);
		final FormData fd_customerNameLabel = new FormData();
		fd_customerNameLabel.bottom = new FormAttachment(0, 52);
		fd_customerNameLabel.top = new FormAttachment(0, 39);
		fd_customerNameLabel.right = new FormAttachment(0, 369);
		fd_customerNameLabel.left = new FormAttachment(0, 294);
		customerNameLabel.setLayoutData(fd_customerNameLabel);
		customerNameLabel.setForeground(SWTResourceManager.getColor(0, 0, 255));
		customerNameLabel.setFont(SWTResourceManager.getFont("Tahoma", 8, SWT.NONE));

		inputCustomerName = toolkit.createText(inputComposite, null, SWT.READ_ONLY);
		final FormData fd_inputCustomerName = new FormData();
		fd_inputCustomerName.bottom = new FormAttachment(0, 58);
		fd_inputCustomerName.top = new FormAttachment(0, 39);
		fd_inputCustomerName.right = new FormAttachment(0, 554);
		fd_inputCustomerName.left = new FormAttachment(0, 375);
		inputCustomerName.setLayoutData(fd_inputCustomerName);
		inputCustomerName.setEditable(false);
		

		final Label addressLabel = toolkit.createLabel(inputComposite, "Address", SWT.NONE);
		final FormData fd_addressLabel = new FormData();
		fd_addressLabel.bottom = new FormAttachment(0, 52);
		fd_addressLabel.top = new FormAttachment(0, 39);
		fd_addressLabel.right = new FormAttachment(0, 642);
		fd_addressLabel.left = new FormAttachment(0, 603);
		addressLabel.setLayoutData(fd_addressLabel);
		addressLabel.setForeground(SWTResourceManager.getColor(0, 0, 255));
		addressLabel.setFont(SWTResourceManager.getFont("Tahoma", 8, SWT.NONE));
		
		inputAddress = toolkit.createText(inputComposite, null, SWT.READ_ONLY);
		final FormData fd_inputAddress = new FormData();
		fd_inputAddress.bottom = new FormAttachment(0, 58);
		fd_inputAddress.top = new FormAttachment(0, 39);
		fd_inputAddress.right = new FormAttachment(0, 900);
		fd_inputAddress.left = new FormAttachment(0, 678);
		inputAddress.setLayoutData(fd_inputAddress);
		inputAddress.setEditable(false);

		Label contractNumberLabel;
		contractNumberLabel = toolkit.createLabel(inputComposite, "Contract number", SWT.NONE);
		final FormData fd_contractNumberLabel = new FormData();
		fd_contractNumberLabel.bottom = new FormAttachment(0, 81);
		fd_contractNumberLabel.top = new FormAttachment(0, 68);
		fd_contractNumberLabel.right = new FormAttachment(0, 91);
		fd_contractNumberLabel.left = new FormAttachment(0, 10);
		contractNumberLabel.setLayoutData(fd_contractNumberLabel);
		contractNumberLabel.setForeground(SWTResourceManager.getColor(0, 0, 255));
		contractNumberLabel.setFont(SWTResourceManager.getFont("Tahoma", 8, SWT.NONE));

		inputContractNumber = toolkit.createText(inputComposite, null, SWT.NONE);
		final FormData fd_inputContractNumber = new FormData();
		fd_inputContractNumber.bottom = new FormAttachment(0, 87);
		fd_inputContractNumber.top = new FormAttachment(0, 68);
		fd_inputContractNumber.right = new FormAttachment(0, 213);
		fd_inputContractNumber.left = new FormAttachment(0, 98);
		inputContractNumber.setLayoutData(fd_inputContractNumber);
		inputContractNumber.addKeyListener(new KeyListener(){

			public void keyPressed(KeyEvent e) {
				if (e.keyCode == SWT.F5) {
					doSelectContractNumber();
				}
			}

			public void keyReleased(KeyEvent e) {
				setDirty(true);
			}
			
		});
		
		final Label typeLabel = toolkit.createLabel(inputComposite, "Type", SWT.NONE);
		final FormData fd_typeLabel = new FormData();
		fd_typeLabel.bottom = new FormAttachment(0, 81);
		fd_typeLabel.top = new FormAttachment(0, 68);
		fd_typeLabel.right = new FormAttachment(0, 333);
		fd_typeLabel.left = new FormAttachment(0, 294);
		typeLabel.setLayoutData(fd_typeLabel);
		typeLabel.setForeground(SWTResourceManager.getColor(0, 0, 255));
		typeLabel.setFont(SWTResourceManager.getFont("Tahoma", 8, SWT.NONE));

		inputType = toolkit.createText(inputComposite, null, SWT.NONE);
		final FormData fd_inputType = new FormData();
		fd_inputType.bottom = new FormAttachment(0, 87);
		fd_inputType.top = new FormAttachment(0, 68);
		fd_inputType.right = new FormAttachment(0, 528);
		fd_inputType.left = new FormAttachment(0, 375);
		inputType.setLayoutData(fd_inputType);
		inputType.addKeyListener(new KeyListener() {

			public void keyPressed(KeyEvent e) {
				if (e.keyCode == SWT.F5) {
					doSelectType();
				}
			}

			public void keyReleased(KeyEvent e) {
				setDirty(true);
			}
			
		});
		
		Label serviceDetailLabel;
		serviceDetailLabel = toolkit.createLabel(inputComposite, "Service detail", SWT.NONE);
		final FormData fd_serviceDetailLabel = new FormData();
		fd_serviceDetailLabel.bottom = new FormAttachment(0, 81);
		fd_serviceDetailLabel.top = new FormAttachment(0, 68);
		fd_serviceDetailLabel.right = new FormAttachment(0, 673);
		fd_serviceDetailLabel.left = new FormAttachment(0, 603);
		serviceDetailLabel.setLayoutData(fd_serviceDetailLabel);
		serviceDetailLabel.setForeground(SWTResourceManager.getColor(0, 0, 255));
		serviceDetailLabel.setFont(SWTResourceManager.getFont("Tahoma", 8, SWT.NONE));

		inputServiceDetail = toolkit.createText(inputComposite, null, SWT.WRAP);
		final FormData fd_inputServiceDetail = new FormData();
		fd_inputServiceDetail.bottom = new FormAttachment(0, 116);
		fd_inputServiceDetail.top = new FormAttachment(0, 68);
		fd_inputServiceDetail.right = new FormAttachment(0, 900);
		fd_inputServiceDetail.left = new FormAttachment(0, 678);
		inputServiceDetail.setLayoutData(fd_inputServiceDetail);

		final Label dateLabel = toolkit.createLabel(inputComposite, "Date", SWT.NONE);
		final FormData fd_dateLabel = new FormData();
		fd_dateLabel.bottom = new FormAttachment(0, 110);
		fd_dateLabel.top = new FormAttachment(0, 97);
		fd_dateLabel.right = new FormAttachment(0, 45);
		fd_dateLabel.left = new FormAttachment(0, 10);
		dateLabel.setLayoutData(fd_dateLabel);
		dateLabel.setForeground(SWTResourceManager.getColor(0, 0, 255));
		dateLabel.setFont(SWTResourceManager.getFont("Tahoma", 8, SWT.NONE));

		inputDate = new DateChooserCombo(inputComposite, SWT.BORDER);
		final FormData fd_inputDate = new FormData();
		fd_inputDate.bottom = new FormAttachment(0, 116);
		fd_inputDate.top = new FormAttachment(0, 97);
		fd_inputDate.right = new FormAttachment(0, 240);
		fd_inputDate.left = new FormAttachment(0, 98);
		inputDate.setLayoutData(fd_inputDate);
		inputDate.setFormatter(new DateFormatter(Activator.getDefault().getDateFormatTypePreferences()));
		inputDate.addKeyListener(new KeyListener() {

			public void keyPressed(KeyEvent e) {
				
			}

			public void keyReleased(KeyEvent e) {
				setDirty(true);
			}
			
		});
		Label fromLabel;
		fromLabel = toolkit.createLabel(inputComposite, "From", SWT.NONE);
		final FormData fd_fromLabel = new FormData();
		fd_fromLabel.bottom = new FormAttachment(0, 110);
		fd_fromLabel.top = new FormAttachment(0, 97);
		fd_fromLabel.right = new FormAttachment(0, 321);
		fd_fromLabel.left = new FormAttachment(0, 294);
		fromLabel.setLayoutData(fd_fromLabel);
		fromLabel.setForeground(SWTResourceManager.getColor(0, 0, 255));
		fromLabel.setFont(SWTResourceManager.getFont("Tahoma", 8, SWT.NONE));

		inputFrom = toolkit.createText(inputComposite, null, SWT.NONE);
		final FormData fd_inputFrom = new FormData();
		fd_inputFrom.bottom = new FormAttachment(0, 116);
		fd_inputFrom.top = new FormAttachment(0, 97);
		fd_inputFrom.right = new FormAttachment(0, 451);
		fd_inputFrom.left = new FormAttachment(0, 375);
		inputFrom.setLayoutData(fd_inputFrom);
		inputFrom.addKeyListener(new KeyListener() {

			public void keyPressed(KeyEvent e) {
			}

			public void keyReleased(KeyEvent e) {
				setDirty(true);
			}
			
		});
		fromTextFormat = new FormattedText(inputFrom);
		fromTextFormat.setFormatter(new TimeFormatter("hh:mm:a"));

		Label toLabel;
		toLabel = toolkit.createLabel(inputComposite, "To", SWT.NONE);
		final FormData fd_toLabel = new FormData();
		fd_toLabel.bottom = new FormAttachment(0, 110);
		fd_toLabel.top = new FormAttachment(0, 97);
		fd_toLabel.right = new FormAttachment(0, 472);
		fd_toLabel.left = new FormAttachment(0, 460);
		toLabel.setLayoutData(fd_toLabel);
		toLabel.setForeground(SWTResourceManager.getColor(0, 0, 255));
		toLabel.setFont(SWTResourceManager.getFont("Tahoma", 8, SWT.NONE));

		inputTo = toolkit.createText(inputComposite, null, SWT.NONE);
		final FormData fd_inputTo = new FormData();
		fd_inputTo.bottom = new FormAttachment(0, 116);
		fd_inputTo.top = new FormAttachment(0, 97);
		fd_inputTo.right = new FormAttachment(0, 554);
		fd_inputTo.left = new FormAttachment(0, 478);
		inputTo.setLayoutData(fd_inputTo);
		inputTo.addKeyListener(new KeyListener() {

			public void keyPressed(KeyEvent e) {
			}

			public void keyReleased(KeyEvent e) {
				setDirty(true);
			}
			
		});
		toTextFormat = new FormattedText(inputTo);
		toTextFormat.setFormatter(new TimeFormatter("hh:mm:a"));

		Composite inputButtonBar;
		inputButtonBar = new Composite(inputComposite, SWT.NONE);
		final FormData fd_inputButtonBar = new FormData();
		fd_inputButtonBar.bottom = new FormAttachment(0, 157);
		fd_inputButtonBar.top = new FormAttachment(0, 135);
		fd_inputButtonBar.right = new FormAttachment(0, 240);
		fd_inputButtonBar.left = new FormAttachment(0, 10);
		inputButtonBar.setLayoutData(fd_inputButtonBar);
		inputButtonBar.setLayout(new FillLayout());
		toolkit.adapt(inputButtonBar);

		final Button saveButton = toolkit.createButton(inputButtonBar, "&Save", SWT.NONE);
		saveButton.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(SelectionEvent e) {
				doSave();
			}
		});
		saveButton.setImage(ResourceManager.getPluginImage(Activator.getDefault(), "icons/actions/save_all.png"));

		final Button cancelButton = toolkit.createButton(inputButtonBar, "&Cancel", SWT.NONE);
		cancelButton.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(SelectionEvent e) {
				doCancel();
			}
		});
		cancelButton.setImage(ResourceManager.getPluginImage(Activator.getDefault(), "icons/actions/exit.png"));

		final Button inputClearButton = toolkit.createButton(inputButtonBar, "Clea&r", SWT.NONE);
		inputClearButton.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(SelectionEvent e) {
				doClearInputSection();
			}
		});
		inputClearButton.setImage(ResourceManager.getPluginImage(Activator.getDefault(), "icons/actions/eraser.png"));

		Button browseResourceIDButton;
		browseResourceIDButton = toolkit.createButton(inputComposite, "", SWT.NONE);
		final FormData fd_browseResourceIDButton = new FormData();
		fd_browseResourceIDButton.bottom = new FormAttachment(0, 29);
		fd_browseResourceIDButton.top = new FormAttachment(0, 10);
		fd_browseResourceIDButton.right = new FormAttachment(0, 554);
		fd_browseResourceIDButton.left = new FormAttachment(0, 527);
		browseResourceIDButton.setLayoutData(fd_browseResourceIDButton);
		browseResourceIDButton.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(SelectionEvent e) {
				doSelectResourceId();
			}
		});
		browseResourceIDButton.setImage(ResourceManager.getPluginImage(Activator.getDefault(), "icons/actions/viewmag+.png"));

		final Button browseCustomeCodeButton = toolkit.createButton(inputComposite, "", SWT.NONE);
		final FormData fd_browseCustomeCodeButton = new FormData();
		fd_browseCustomeCodeButton.bottom = new FormAttachment(0, 58);
		fd_browseCustomeCodeButton.top = new FormAttachment(0, 39);
		fd_browseCustomeCodeButton.right = new FormAttachment(0, 240);
		fd_browseCustomeCodeButton.left = new FormAttachment(0, 213);
		browseCustomeCodeButton.setLayoutData(fd_browseCustomeCodeButton);
		browseCustomeCodeButton.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(SelectionEvent e) {
				doSelectCustomerCode();
			}
		});
		browseCustomeCodeButton.setImage(ResourceManager.getPluginImage(Activator.getDefault(), "icons/actions/viewmag+.png"));

		final Button browseCustomeCodeButton_1 = toolkit.createButton(inputComposite, "", SWT.NONE);
		final FormData fd_browseCustomeCodeButton_1 = new FormData();
		fd_browseCustomeCodeButton_1.bottom = new FormAttachment(0, 87);
		fd_browseCustomeCodeButton_1.top = new FormAttachment(0, 68);
		fd_browseCustomeCodeButton_1.right = new FormAttachment(0, 240);
		fd_browseCustomeCodeButton_1.left = new FormAttachment(0, 213);
		browseCustomeCodeButton_1.setLayoutData(fd_browseCustomeCodeButton_1);
		browseCustomeCodeButton_1.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(SelectionEvent e) {
				doSelectContractNumber();
			}
		});
		browseCustomeCodeButton_1.setImage(ResourceManager.getPluginImage(Activator.getDefault(), "icons/actions/viewmag+.png"));

		Button browseCustomeCodeButton_1_1;
		browseCustomeCodeButton_1_1 = toolkit.createButton(inputComposite, "", SWT.NONE);
		final FormData fd_browseCustomeCodeButton_1_1 = new FormData();
		fd_browseCustomeCodeButton_1_1.bottom = new FormAttachment(0, 87);
		fd_browseCustomeCodeButton_1_1.top = new FormAttachment(0, 68);
		fd_browseCustomeCodeButton_1_1.right = new FormAttachment(0, 554);
		fd_browseCustomeCodeButton_1_1.left = new FormAttachment(0, 527);
		browseCustomeCodeButton_1_1.setLayoutData(fd_browseCustomeCodeButton_1_1);
		browseCustomeCodeButton_1_1.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(SelectionEvent e) {
				doSelectType();
			}
		});
		browseCustomeCodeButton_1_1.setImage(ResourceManager.getPluginImage(Activator.getDefault(), "icons/actions/viewmag+.png"));

		serviceCardForm.setText("Service Card");
	}

	protected void doDelete() {
		ServiceCardBean element = (ServiceCardBean) ((StructuredSelection)tableViewer.getSelection()).getFirstElement();
		if (null != element) {
			if (MessageDialog.openConfirm(null, "Confirm", "Do you really want to delete?")) {
				try {
					if (element.getId() > 0) {
						element.delete();
					} 
					inputList.remove(element);
					tableViewer.setInput(inputList);
				} catch (SQLException e) {
					e.printStackTrace();
					MessageDialog.openError(null, "Error", e.getMessage());
				}
			}
		} else {
			MessageDialog.openError(null, "Error", "Please select the service card to delete");
		}
		
	}

	protected void doNew() {
		//reset cardId to zero in case add new ServiceCard
		cardId = 0;
		doClearInputSection();
		entereditServiceCardSection.setExpanded(true);
		generalInformationSection.setExpanded(false);
	}

	protected void doCancel() {
		doClearInputSection();
		entereditServiceCardSection.setExpanded(false);
		generalInformationSection.setExpanded(true);
	}

	protected void doEdit() {
		ServiceCardBean element = (ServiceCardBean) ((IStructuredSelection)tableViewer.getSelection()).getFirstElement();
		if (null != element) {
			entereditServiceCardSection.setExpanded(true);
			generalInformationSection.setExpanded(false);
			try {
			cardId = element.getId();
			inputCardNumber.setText(DpUtils.trim(element.getCardNumber()));
			inputContractNumber.setText(DpUtils.trim(element.getContractNumber()));
			inputCustomerCode.setText(DpUtils.trim(element.getCustomerCode()));
			inputCustomerName.setText(DpUtils.trim(element.getCustomerName()));
			inputAddress.setText(DpUtils.trim(element.getAddress()));
			inputDate.setValue(element.getDate());
			inputResourceID.setText(DpUtils.trim(element.getResourceId()));
			inputFullName.setText(DpUtils.trim(element.getFullName()));
			inputServiceDetail.setText(DpUtils.trim(element.getServiceDetail()));
			inputType.setText(DpUtils.trim(element.getType()));
			inputFrom.setText(DpUtils.trim(element.getFromTime()));
			inputTo.setText(DpUtils.trim(element.getToTime()));
//			fromTextFormat.setValue(element.getFromTime());
//			toTextFormat.setValue(element.getToTime());
			} catch (Exception e) {
				e.printStackTrace();
			}
		} else {
			MessageDialog.openError(null, "Error", "Please select the service card to edit");
		}
	}

	protected void doSearch() {
		try {
			if (null != fromDate.getValue()) {
				criteria.setFromDate(new java.sql.Date(fromDate.getValue()
						.getTime()));
			} else {
				criteria.setFromDate(null);
			}
			if (null != toDate.getValue()) {
				criteria.setToDate(new java.sql.Date(toDate.getValue()
						.getTime()));
			} else {
				criteria.setToDate(null);
			}
			if (null != fromDate.getValue() && null != toDate.getValue() && fromDate.getValue().after(toDate.getValue())) {
				MessageDialog.openError(null, "Error", "From date can not be after to date");
				return;
			}
			criteria.setResourceId(resource.getText());
			criteria.setServiceCard(serviceCard.getText());
			criteria.setContractNumber(contract.getText());
			criteria.setCustomerCode(customerCode.getText());
			criteria.setCustomerName(customerName.getText());
			criteria.setAddress(address.getText());
			inputList = criteria.search();
			tableViewer.setInput(inputList);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	protected void doClearInputSection() {
		cardId = 0;
		inputCardNumber.setText("");
		inputResourceID.setText("");
		inputContractNumber.setText("");
		inputCustomerCode.setText("");
		inputCustomerName.setText("");
		inputDate.setValue(null);
		fromTextFormat.setValue(null);
		toTextFormat.setValue(null);
		inputType.setText("");
		inputServiceDetail.setText("");
		inputFullName.setText("");
		inputAddress.setText("");
	}

	protected void doClearCriteriaSection() {
		fromDate.setValue(null);
		toDate.setValue(null);
		resource.setText("");
		serviceCard.setText("");
		contract.setText("");
		customerCode.setText("");
		customerName.setText("");
		address.setText("");
	}

	protected void doExport() {
		FileDialog fileDialog = new FileDialog(this.getEditorSite().getShell(), SWT.SAVE);
		fileDialog.setFilterExtensions(new String[] { "*.xls" });
		fileDialog.setFilterNames(new String[] { "Excel files" });
		String reportLocation = fileDialog.open();
		if (null != reportLocation) {
			File file = new File(reportLocation);
			WritableWorkbook resultBook;
			try {
				int beginCol = 0;
				resultBook = Workbook.createWorkbook(file);
				WritableSheet resultSheet = resultBook.createSheet(
						"Result", 0);
				int beginRow = setReportHeader(resultSheet, 0);
				// remove rows before rewrite
				for (int i = beginRow; i < resultSheet.getRows(); i++) {
					resultSheet.removeRow(i);
				}
				
				DateFormat format = new DateFormat(Activator.getDefault()					
						.getDateFormatTypePreferences());
				WritableCellFormat dateFormat = new WritableCellFormat(format);
				
				//other font
				WritableFont defaultFont = new WritableFont(WritableFont.ARIAL, 10, WritableFont.NO_BOLD);
				defaultFont.setColour(Colour.BLACK);
				
				if (null != resultSheet) {
					for (ServiceCardBean card : inputList) {
						resultSheet.addCell(new jxl.write.Label(beginCol++, beginRow, card.getCardNumber()));
						resultSheet.addCell(new jxl.write.Label(beginCol++, beginRow, card.getResourceId()));
						resultSheet.addCell(new jxl.write.Label(beginCol++, beginRow, card.getFullName()));
						if (null != card.getDate() ) {
							resultSheet.addCell(new jxl.write.DateTime(beginCol++, beginRow, card.getDate(), dateFormat));
						} else {
							resultSheet.addCell(new jxl.write.Label(beginCol++, beginRow, ""));
						}
						resultSheet.addCell(new jxl.write.Label(beginCol++, beginRow, card.getFromTime()));
						resultSheet.addCell(new jxl.write.Label(beginCol++, beginRow, card.getToTime()));
						resultSheet.addCell(new jxl.write.Label(beginCol++, beginRow, card.getCustomerCode()));
						resultSheet.addCell(new jxl.write.Label(beginCol++, beginRow, card.getCustomerName()));
						resultSheet.addCell(new jxl.write.Label(beginCol++, beginRow, card.getAddress()));
						resultSheet.addCell(new jxl.write.Label(beginCol++, beginRow, card.getContractNumber()));
						resultSheet.addCell(new jxl.write.Label(beginCol++, beginRow, card.getServiceDetail()));
						resultSheet.addCell(new jxl.write.Label(beginCol++, beginRow++, card.getType()));
						beginCol = 0;
					}
				}
				resultBook.write();
				resultBook.close();
				MessageBox box = new MessageBox(this.getEditorSite().getShell(), SWT.OK | SWT.CANCEL
						| SWT.ICON_INFORMATION);
				box
						.setMessage("Export completed, click OK to open the result file now or click cancel to open it manually later");
				int i = box.open();
				if (i == SWT.OK) {
					Runtime.getRuntime().exec(
							"cmd.exe /C \"" + reportLocation + "\"");
				}
			} catch (IOException e) {
				e.printStackTrace();
			} catch (RowsExceededException e) {
				e.printStackTrace();
			} catch (WriteException e) {
				e.printStackTrace();
			}
		}
}


	private int setReportHeader(WritableSheet resultSheet, int i) {
		WritableCellFormat tf;
//		WritableCellFormat numberFormat = new WritableCellFormat(
//				NumberFormats.FLOAT);
		try {
			WritableFont title = new WritableFont(WritableFont.ARIAL, 20,
					WritableFont.BOLD);
			title.setColour(Colour.BLACK);
			tf = new WritableCellFormat(title);
			tf.setAlignment(Alignment.LEFT);
			resultSheet.addCell(new jxl.write.Label(0, i, "Service Card", tf));
			resultSheet.mergeCells(0, i, 1, i++);
			WritableFont criteriaFont = new WritableFont(WritableFont.ARIAL,
					10, WritableFont.BOLD);
			criteriaFont.setColour(Colour.BLUE);
			WritableCellFormat criteriaFormat = new WritableCellFormat(
					criteriaFont);
			// add an empty row
			i++;
			// Criteria
			WritableFont font = new WritableFont(WritableFont.ARIAL, 10, WritableFont.BOLD);
			WritableCellFormat boldFormat = new WritableCellFormat(font);
			boldFormat.setAlignment(Alignment.LEFT);
			
			WritableFont alinRightFont = new WritableFont(WritableFont.ARIAL, 10, WritableFont.NO_BOLD);
			WritableCellFormat alignRightCellFormat = new WritableCellFormat(alinRightFont);
			alignRightCellFormat.setAlignment(Alignment.RIGHT);
			
			resultSheet.addCell(new jxl.write.Label(0, i++, "General Information", boldFormat));
//			resultSheet.mergeCells(0, i, 3, i);
			
			DateFormat format = new DateFormat(Activator.getDefault()
					.getDateFormatTypePreferences());
			WritableCellFormat dateFormat = new WritableCellFormat(format);
			//1st header row
			resultSheet.addCell(new jxl.write.Label(0, i, "From date",
					criteriaFormat));
			if (null != fromDate.getValue()) {
				resultSheet.addCell(new jxl.write.DateTime(1, i, fromDate.getValue() , dateFormat));
			} else {
				resultSheet.addCell(new Blank(1, i));
			}
			resultSheet.addCell(new jxl.write.Label(2, i, "Resource",criteriaFormat));
			resultSheet.addCell(new jxl.write.Label(3, i, resource.getText()));
			resultSheet.addCell(new jxl.write.Label(4, i, "Customer code", criteriaFormat));
			resultSheet.addCell(new jxl.write.Label(5, i, customerCode.getText()));
			resultSheet.addCell(new jxl.write.Label(6, i, "Customer name", criteriaFormat));
			resultSheet.addCell(new jxl.write.Label(7, i++, customerName.getText()));
			
			//2nd header row
			resultSheet.addCell(new jxl.write.Label(0, i, "To date", criteriaFormat));
			if (null != toDate.getValue()) {
				resultSheet.addCell(new jxl.write.DateTime(1, i, toDate.getValue(), dateFormat));
			} else {
				resultSheet.addCell(new Blank(1, i));
			}
			resultSheet.addCell(new jxl.write.Label(2, i, "Serviec card", criteriaFormat));
			resultSheet.addCell(new jxl.write.Label(3, i, serviceCard.getText()));
			resultSheet.addCell(new jxl.write.Label(4, i, "Contract",criteriaFormat));
			resultSheet.addCell(new jxl.write.Label(5, i, contract.getText()));
			resultSheet.addCell(new jxl.write.Label(6, i, "Address",criteriaFormat));
			resultSheet.addCell(new jxl.write.Label(7, i++, address.getText()));

			//Detail row header
			WritableFont underLineFont = new WritableFont(WritableFont.ARIAL, 10, WritableFont.BOLD, true, UnderlineStyle.SINGLE);
			WritableCellFormat undeLineFontCellFormat = new WritableCellFormat(underLineFont);
			undeLineFontCellFormat.setAlignment(Alignment.LEFT);
			resultSheet.addCell(new jxl.write.Label(0, i++,
					"Detail Information", undeLineFontCellFormat));

			// set font and background color
			WritableFont header = new WritableFont(WritableFont.ARIAL, 10,
					WritableFont.BOLD);
			header.setColour(Colour.WHITE);
			WritableCellFormat hf = new WritableCellFormat(header);
			hf.setBackground(Colour.BLUE);
			hf.setAlignment(Alignment.CENTRE);
			hf.setVerticalAlignment(VerticalAlignment.CENTRE);
			hf.setWrap(true);
			int col = 0;
			resultSheet.setColumnView(col, 20);
			resultSheet.addCell(new jxl.write.Label(col++, i, "Card number", hf));
			resultSheet.setColumnView(col, 15);
			resultSheet.addCell(new jxl.write.Label(col++, i, "Resource ID", hf));
			resultSheet.setColumnView(col, 25);
			resultSheet.addCell(new jxl.write.Label(col++, i, "FullName", hf));
			resultSheet.setColumnView(col, 15);
			resultSheet.addCell(new jxl.write.Label(col++, i, "Date", hf));
			resultSheet.setColumnView(col, 20);
			resultSheet.addCell(new jxl.write.Label(col++, i, "From", hf));
			resultSheet.setColumnView(col, 20);
			resultSheet.addCell(new jxl.write.Label(col++, i, "To", hf));
			resultSheet.setColumnView(col, 15);
			resultSheet.addCell(new jxl.write.Label(col++, i, "Customer code", hf));
			resultSheet.setColumnView(col, 30);
			resultSheet.addCell(new jxl.write.Label(col++, i, "Customer name", hf));
			resultSheet.setColumnView(col, 50);
			resultSheet.addCell(new jxl.write.Label(col++, i, "Address", hf));
			resultSheet.setColumnView(col, 20);
			resultSheet.addCell(new jxl.write.Label(col++, i, "Contract number", hf));
			resultSheet.setColumnView(col, 25);
			resultSheet.addCell(new jxl.write.Label(col++, i, "Service detail", hf));
			resultSheet.setColumnView(col, 30);
			resultSheet.addCell(new jxl.write.Label(col, i++, "Type", hf));
			return i;
		} catch (WriteException e) {
			e.printStackTrace();
		}
		return 0;
	}


	protected void doClose() {
		if (isDirty) {
			MessageDialog dlg = new MessageDialog(
					this.getEditorSite().getShell(),
					"Save and Exit",
					null,
					"Service card has being edited. Do you want to save it before exit?",
					MessageDialog.QUESTION, new String[] { "Yes", "No",
							"Cancel" }, 0);
				switch (dlg.open()) {
				case 0:
					boolean isSaved = doSave();
					if (isSaved) {
						this.getEditorSite().getWorkbenchWindow().getActivePage().closeEditor(this, false);
						setDirty(false);
					}
					break;
				case 1:
					this.getEditorSite().getWorkbenchWindow().getActivePage().closeEditor(this, false);
					break;
				default:
					return;
			}  
		} else {
			this.getEditorSite().getWorkbenchWindow().getActivePage().closeEditor(this, false);
		}
	}

	private void doSelectType() {
		SelectItemCodeHeader header = new SelectItemCodeHeader(
				Display.getCurrent().getActiveShell(),
				"select selcode as code, oms30_0 as description from demand_issuingpurpose order by code");
		if (header.open() == Dialog.OK) {
			MyModel item = (MyModel) header.getSelectedObject();
			if (null != item) {
				inputType.setText(DpUtils.trim(item.getDescription()));
			}
			setDirty(true);
			inputServiceDetail.setFocus();
		}
	}


	private void doSelectContractNumber() {
		String sql = "select contractnumber as code, contractdescription as description from demand_contractinformation";
		if (null != inputCustomerCode.getText() && inputCustomerCode.getText().length() > 0) {
			sql += " where rtrim(ltrim(customercode)) = '" + DpUtils.trim(inputCustomerCode.getText()) + "'";
		}
		sql += " order by code";
		SelectItemCodeHeader header = new SelectItemCodeHeader(
				Display.getCurrent().getActiveShell(), sql);
		header.setCodeLabel("Contract number");
		header.setDescriptionLabel("Contract description");
		if (header.open() == Dialog.OK) {
			MyModel item = (MyModel) header.getSelectedObject();
			if (null != item) {
				inputContractNumber.setText(DpUtils.trim(item.getCode()));
			}
			setDirty(true);
			inputType.setFocus();
		}
	}

	private void doSelectResourceId() {
		SelectItemCodeHeader header = new SelectItemCodeHeader(
				Display.getCurrent().getActiveShell(),
				"select res_id as code, fullname as description from demand_resourcelist order by code");
		header.setCodeLabel("Resource ID");
		header.setDescriptionLabel("Full Name");
		if (header.open() == Dialog.OK) {
			MyModel item = (MyModel) header.getSelectedObject();
			if (null != item) {
				inputResourceID.setText(DpUtils.trim(item.getCode()));
				inputFullName.setText(DpUtils.trim(item.getDescription()));
			}
			setDirty(true);
			inputCustomerCode.setFocus();
		}
	}

	private void doSelectCustomerCode() {
		SelectCustomerHeader header = new SelectCustomerHeader(Display.getCurrent().getActiveShell(),"select cmp_code as code, cmp_name as name, cmp_fadd1 as address from demand_customerlist order by code"); 
		if (header.open() == Dialog.OK) {
			CustomerBean item = (CustomerBean) header.getSelectedModel();
			if (null != item) {
				inputCustomerCode.setText(DpUtils.trim(item.getCustomerCode()));
				inputCustomerName.setText(DpUtils.trim(item.getCustomerName()));
				inputAddress.setText(DpUtils.trim(item.getAddress()));
			}
			setDirty(true);
			inputContractNumber.setFocus();
		}
	}

	public void initData() {
		setDirty(false);
		criteria = new ServiceCardCriteria();
		inputList = criteria.search();
	}
	
	private int doValidate(List<ServiceCardBean> list) {
		if (null != list && !list.isEmpty()) {
			for (ServiceCardBean bean : list) {
				if (null == bean.getCardNumber() || bean.getCardNumber().length() == 0) {
					return 0;
				}
				if (null == bean.getResourceId() || bean.getResourceId().length() == 0) {
					return 1;
				}
				if (null == bean.getDate()) {
					return 2;
				}
				if (null == bean.getCustomerCode() || bean.getCustomerCode().length() == 0) {
					return 5;
				}
				if (null == bean.getCustomerName() || bean.getCustomerName().length() == 0) {
					return 6;
				}
				if (null == bean.getContractNumber() || bean.getContractNumber().length() == 0) {
					return 7;
				}
				if (null == bean.getType() || bean.getType().length() == 0) {
					return 9;
				}
				if (cardId == 0 && !isAvailableServiceCode(DpUtils.trim(bean.getCardNumber()))) {
					return 10;
				}
			}
		}
		return -1;
	}
	
	private boolean isAvailableServiceCode (String code) {
		String sql = "select cardnumber as code from demand_lux_servicecard where cardnumber = ?";
		QueryRunner runner = new QueryRunner(DpUtils.getDataSource());
		try {
			return (Boolean) runner.query(sql, code, new ResultSetHandler() {

				public Object handle(ResultSet rs) throws SQLException {
					while (rs.next()) {
						return false;
					}
					return true;
				}
				
			});
		} catch (SQLException e) {
			e.printStackTrace();
			MessageDialog.openError(null, "Error", e.getMessage());
			return false;
		}
	}
	
	@Override
	public void setFocus() {
		// Set the focus
	}

	@Override
	public void doSave(IProgressMonitor monitor) {
	}
	
	public boolean doSave() {
		ServiceCardBean cardBean = new ServiceCardBean();
		//if cardId == 0 then insert else update
		cardBean.setId(cardId);
		cardBean.setCardNumber(inputCardNumber.getText());
		cardBean.setContractNumber(inputContractNumber.getText());
		cardBean.setCustomerCode(inputCustomerCode.getText());
		cardBean.setCustomerName(inputCustomerName.getText());
		cardBean.setAddress(inputAddress.getText());
		cardBean.setDate(inputDate.getValue());
		cardBean.setFromTime(inputFrom.getText());
		cardBean.setToTime(inputTo.getText());
		cardBean.setResourceId(inputResourceID.getText());
		cardBean.setFullName(inputFullName.getText());
		cardBean.setServiceDetail(inputServiceDetail.getText());
		cardBean.setType(inputType.getText());
		updateList.add(cardBean);
		// Do the Save operation
		switch (doValidate(updateList)) {
		case 0:
			MessageDialog.openError(null, "Error", "Card number can not be empty");
			updateList.clear();
			return false;
		case 1:
			MessageDialog.openError(null, "Error", "Resource can not be empty");
			updateList.clear();
			return false;
		case 2:	
			MessageDialog.openError(null, "Error", "Date can not be empty");
			updateList.clear();
			return false;
		case 5:	
			MessageDialog.openError(null, "Error", "Customer code can not be empty");
			updateList.clear();
			return false;
		case 6:	
			MessageDialog.openError(null, "Error", "Customer name can not be empty");
			updateList.clear();
			return false;
		case 7:	
			MessageDialog.openError(null, "Error", "Contract number can not be empty");
			updateList.clear();
			return false;
		case 9:	
			MessageDialog.openError(null, "Error", "Type can not be empty");
			updateList.clear();
			return false;
		case 10:
			MessageDialog.openError(null, "Error", "Card number is existed, enter a new number please");
			updateList.clear();
			return false;
		}
		try {
			ServiceCardManager.saveServiceCards(updateList);
			MessageDialog.openInformation(null, "Saved", "Service cards were saved");
			updateList.clear();
		} catch (SQLException e) {
			e.printStackTrace();
			MessageDialog.openError(null, "Error", e.getMessage());
		}
		setDirty(false);
		doSearch();
		doClearInputSection();
		return true;
	}
	
	@Override
	public void doSaveAs() {
		// Do the Save As operation
	}

	@Override
	public void init(IEditorSite site, IEditorInput input)
			throws PartInitException {
		setSite(site);
		setInput(input);
		setPartName("Service card");
		setTitleToolTip("Service Card Editor");
	}

	private boolean isDirty;

	public void setDirty(boolean isDirty) {
		this.isDirty = isDirty;
	}
	
	@Override
	public boolean isDirty() {
		return isDirty;
	}

	@Override
	public boolean isSaveAsAllowed() {
		return false;
	}
	
	
	public class ServiceCardContentProvider implements IStructuredContentProvider {

		public Object[] getElements(Object inputElement) {
			return inputList.toArray(new ServiceCardBean[0]);
		}

		public void dispose() {
		}

		public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
		}
		
	}


	public ArrayList<ServiceCardBean> getUpdateList() {
		return updateList;
	}


	public void setUpdateList(ArrayList<ServiceCardBean> updateList) {
		this.updateList = updateList;
	}

}
